package com.leiyuan.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.leiyuan.content.mapper.CourseTeacherMapper;
import com.leiyuan.content.service.CourseTeacherService;
import com.leiyuan.dto.CourseTeacherDto;
import com.leiyuan.exection.ElearningPlusException;
import com.leiyuan.po.CourseTeacher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author leiyuan
 * @version 1.0
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<CourseTeacherDto> queryCourseTeacher(Long courseId) {

        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId, courseId));
        if (courseTeachers == null){
            return null;
        }

        List<CourseTeacherDto> courseTeacherDtos = new ArrayList<>();
        for (CourseTeacher courseTeacher :
                courseTeachers) {
            CourseTeacherDto courseTeacherDto = new CourseTeacherDto();
            BeanUtils.copyProperties(courseTeacher,courseTeacherDto);
            courseTeacherDtos.add(courseTeacherDto);
        }
        return courseTeacherDtos;
    }

    @Override
    public CourseTeacherDto createCourseTeacher(CourseTeacherDto courseTeacherDto) {
        Long courseId = courseTeacherDto.getCourseId();
        String teacherName = courseTeacherDto.getTeacherName();

        CourseTeacher teacher = courseTeacherMapper.selectOne(new LambdaQueryWrapper<CourseTeacher>()
                .eq(CourseTeacher::getCourseId, courseId)
                .eq(CourseTeacher::getTeacherName, teacherName));

        CourseTeacher courseTeacher = new CourseTeacher();
        BeanUtils.copyProperties(courseTeacherDto,courseTeacher);
        if (teacher != null){
            //当前操作为修改操作
            courseTeacherMapper.updateById(courseTeacher);
        }else {
            //当前操作为新增操作
            courseTeacher.setCreateDate(LocalDateTime.now());
            courseTeacherMapper.insert(courseTeacher);
        }
        return courseTeacherDto;
    }

    @Override
    public void removeCourseTeacher(Long courseId, Long id) {
        int i = courseTeacherMapper.deleteById(id);
        if (i<=0){
            throw new ElearningPlusException("删除失败，请稍后再试");
        }
    }
}
